//
//  ActivityListTableViewController.swift
//  健身宝
//
//  Created by hzt on 2017/9/29.
//  Copyright © 2017年 hzt. All rights reserved.
//

import UIKit

class HomeTableViewController: UITableViewController,activityListDelegate,masterListDelegate,contestListDelegate {
    var activityList:NSMutableArray!
    var masterList:NSMutableArray!
    var contestList:NSMutableArray!
    var askList:NSMutableArray!
    var activityBtn:UIButton!
    var masterBtn:UIButton!
    var contestBtn:UIButton!
    var flag:Bool = true
    var activityID:NSString!
    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
        getActivityList()
        getMasterList()
        getContestList()
        getAskList()
            }

    func setView(){
    tableView.backgroundColor = UIColor.lightGray
    tableView.refreshControl = UIRefreshControl()
    tableView.refreshControl?.addTarget(self, action: #selector(refreshData), for: .valueChanged)
    tableView.register(activityListCell.self, forCellReuseIdentifier: "activityListCell")
    tableView.register(masterListCell.self, forCellReuseIdentifier: "masterListCell")
    tableView.register(contestListCell.self, forCellReuseIdentifier: "contestListCell")
    let headView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 40))
    headView.backgroundColor = UIColor.blue
        
        activityBtn = UIButton(frame: CGRect(x: 0, y: headView.bounds.height-40, width: view.bounds.width/3, height: 40))
        activityBtn.backgroundColor = UIColor.gray
        activityBtn.addTarget(self, action: #selector(showActivityList), for: .touchUpInside)
        activityBtn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        activityBtn.setTitle("精选活动", for: .normal)
        activityBtn.titleLabel?.textAlignment = .center
        headView.addSubview(activityBtn)
        
        masterBtn = UIButton(frame: CGRect(x: view.bounds.width/3, y: headView.bounds.height-40, width: view.bounds.width/3, height: 40))
        masterBtn.backgroundColor = UIColor.gray
        masterBtn.addTarget(self, action: #selector(showMasterList), for: .touchUpInside)
        masterBtn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        masterBtn.setTitle("权威大师", for: .normal)
        masterBtn.titleLabel?.textAlignment = .center
        headView.addSubview(masterBtn)
        
        contestBtn = UIButton(frame: CGRect(x: view.bounds.width/3*2, y: headView.bounds.height-40, width: view.bounds.width/3, height: 40))
        contestBtn.backgroundColor = UIColor.gray
        contestBtn.addTarget(self, action: #selector(showContestList), for: .touchUpInside)
        contestBtn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        contestBtn.setTitle("最近比赛", for: .normal)
        contestBtn.titleLabel?.textAlignment = .center
        headView.addSubview(contestBtn)
        
        tableView.tableHeaderView = headView
        
        let footView = UIView()
        tableView.tableFooterView = footView

    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let basicCell:UITableViewCell? = nil
        if flag && activityList != nil{
            let cell = tableView.dequeueReusableCell(withIdentifier: "activityListCell", for: indexPath) as! activityListCell
            cell.selectionStyle = .none
            let dict = activityList[indexPath.row] as! NSDictionary
            //print(dict)
            cell.indexPath = indexPath
            cell.activityDelegate = self
            let pURL = "http://172.24.10.175/workout/Uploads/"
            let Thumb = dict["thumb"] as? String
            var imageUrl = URL(string: (pURL+Thumb!))
            cell.AcitivityPhoto!.setImageWith(imageUrl, placeholderImage: UIImage(named: "placeHolder"))
            //cell.AcitivityPhoto.image = dict["thumb"] as? UIImage
            cell.Activity_name.text = dict["activity_name"] as? String
            cell.Introduction.text =  dict["introduction"] as? String
            return cell
        }else if !flag && masterList != nil{
            let cell = tableView.dequeueReusableCell(withIdentifier: "masterListCell", for: indexPath) as! masterListCell
            let dict = masterList[indexPath.row] as! NSDictionary
            //print(dict)
            cell.selectionStyle = .none
            cell.indexPath = indexPath
            cell.masterDelegate = self
            let pURL = "http://172.24.10.175/workout/Uploads/"
            let Thumb = dict["thumb"] as? String
            var imageUrl = URL(string: (pURL+Thumb!))
            cell.MasterPhoto!.setImageWith(imageUrl, placeholderImage: UIImage(named: "placeHolder"))
            cell.Actcate_name.text = dict["actcate_name"] as? String
            cell.Introduction.text = dict["introduction"] as? String
            cell.Realname.text = dict["realname"] as? String
            return cell
        }else if !flag && contestList != nil{
            let cell = tableView.dequeueReusableCell(withIdentifier: "contestListCell", for: indexPath) as! contestListCell
            let dict = contestList[indexPath.row] as! NSDictionary
            //print(dict)
            cell.selectionStyle = .none
            cell.indexPath = indexPath
            cell.contestDelegate = self
            let pURL = "http://172.24.10.175/workout/Uploads/"
            let Thumb = dict["thumb"] as? String
            var imageUrl = URL(string: (pURL+Thumb!))
            cell.ContestPhoto!.setImageWith(imageUrl, placeholderImage: UIImage(named: "placeHolder"))

            //cell.ContestPhoto.image = dict["thumb"] as? UIImage
            cell.Name.text = dict["name"] as? String
            return cell
        }
        return basicCell!
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    
    func showActivityList(){
            flag = true
//            activityList = nil
            masterList = nil
            contestList = nil
            self.getActivityList()
            tableView.reloadData()
        
    }
    func showMasterList(){
            flag = false
//            masterList = nil
            contestList = nil
            activityList = nil
            self.getMasterList()
            tableView.reloadData()
        
        
        
    }
    
    func showContestList(){
        
            flag = false
            masterList = nil
            activityList = nil
            self.getContestList()
            tableView.reloadData()
            }
    
    
    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if flag && activityList != nil{
            return activityList.count
        }else if !flag && masterList != nil{
            return masterList.count
        }else if !flag && contestList != nil{
            return contestList.count
        }
        return 0
    }

    
    
    func getActivityList(){
        let urlStr = RO_GetActivityList
        let paraDict = ["sessionid":SessionID]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
            let array = data as! NSArray
            //print(array)
            self.activityList = array.mutableCopy() as! NSMutableArray
            self.tableView.reloadData()
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            print(response!.debugDescription)
        }

    }
    
    func getMasterList(){
        let urlStr = RO_GetMasterList
        let paraDict = ["sessionid":SessionID]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
            let array = data as! NSArray
            //print(array)
            self.masterList = array.mutableCopy() as! NSMutableArray
            self.tableView.reloadData()
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            print(response!.debugDescription)
        }
    }
    
    func getContestList(){
        let urlStr = RO_GetContestList
        let paraDict = ["sessionid":SessionID]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
            let array = data as! NSArray
            //print(array)
            self.contestList = array.mutableCopy() as! NSMutableArray
            self.tableView.reloadData()
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            print(response!.debugDescription)
        }
    }
    
    func getAskList(){
        let urlStr = RO_AskList
        let paraDict = ["sessionid":SessionID]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
            let array = data as! NSArray
            //print(array)
            self.askList = array.mutableCopy() as! NSMutableArray
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            print(response!.debugDescription)
        }
        
    }
    
    func refreshData(){
        if flag && activityList != nil{
            getActivityList()
            tableView.reloadData()
            tableView.refreshControl?.endRefreshing()
        }else if !flag && masterList != nil{
            getMasterList()
            tableView.reloadData()
            tableView.refreshControl?.endRefreshing()
        }else if !flag && contestList != nil{
            getContestList()
            tableView.reloadData()
            tableView.refreshControl?.endRefreshing()
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if flag{
            return 200
        }else{
            return 200
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if flag && activityList != nil{
            let controller = ActivityDetailViewController()
            controller.infoDict = activityList![indexPath.row] as! NSDictionary
            hidesBottomBarWhenPushed = true
            _ = navigationController?.pushViewController(controller, animated: true)
            hidesBottomBarWhenPushed = false
        }else if !flag && masterList != nil{
            let controller = MasterDetailViewController()
            controller.infoDict = masterList![indexPath.row] as! NSDictionary
            controller.dict = askList![indexPath.row] as! NSDictionary
            hidesBottomBarWhenPushed = true
            _ = navigationController?.pushViewController(controller, animated: true)
            hidesBottomBarWhenPushed = false
        }else if !flag && contestList != nil{
            let controller = ContestDetailViewController()
            controller.infoDict = contestList![indexPath.row] as! NSDictionary
            hidesBottomBarWhenPushed = true
            _ = navigationController?.pushViewController(controller, animated: true)
            hidesBottomBarWhenPushed = false
        }

        
        
        
    }
}
